package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyFavoritesScreen(navController: NavController) {
    val currentUser = UserState.currentUser
    var posts by remember { mutableStateOf<List<CommunityPost>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var currentPage by remember { mutableStateOf(1) }
    var hasMore by remember { mutableStateOf(true) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var postToUnfavorite by remember { mutableStateOf<CommunityPost?>(null) }
    
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }
    
    // 加载数据
    fun loadFavorites(refresh: Boolean = false) {
        if (currentUser == null) return
        
        coroutineScope.launch {
            if (refresh) {
                currentPage = 1
                hasMore = true
                isLoading = true
            } else {
                isLoadingMore = true
            }
            
            try {
                val result = communityApiService.getUserFavorites(currentUser.id, currentPage, 20)
                result.onSuccess { data ->
                    val postsData = data["posts"] as? List<Map<String, Any>> ?: emptyList()
                    val hasMoreData = data["hasMore"] as? Boolean ?: false
                    
                    val newPosts = postsData.map { postData ->
                        CommunityPost(
                            id = (postData["id"] as? Double)?.toLong() ?: 0L,
                            userId = (postData["userId"] as? Double)?.toLong() ?: 0L,
                            author = postData["author"] as? String,
                            title = postData["title"] as? String,
                            content = postData["content"] as? String,
                            likeCount = (postData["likeCount"] as? Double)?.toInt() ?: 0,
                            favoriteCount = (postData["favoriteCount"] as? Double)?.toInt() ?: 0,
                            commentCount = (postData["commentCount"] as? Double)?.toInt() ?: 0,
                            isLiked = postData["isLiked"] as? Boolean ?: false,
                            isFavorited = postData["isFavorited"] as? Boolean ?: false,
                            createdAt = postData["createdAt"] as? String,
                            updatedAt = postData["updatedAt"] as? String
                        )
                    }
                    
                    posts = if (refresh) {
                        newPosts
                    } else {
                        posts + newPosts
                    }
                    
                    hasMore = hasMoreData
                    currentPage++
                }.onFailure { error ->
                    android.util.Log.e("MyFavoritesScreen", "加载收藏失败", error)
                    // 如果API失败，使用模拟数据
                    val mockPosts = if (refresh) {
                        generateMockFavorites(currentUser.id)
                    } else {
                        posts + generateMockFavorites(currentUser.id, currentPage)
                    }
                    posts = mockPosts
                    currentPage++
                    hasMore = mockPosts.size >= 20
                }
                
            } catch (e: Exception) {
                android.util.Log.e("MyFavoritesScreen", "加载收藏异常", e)
                // 如果出现异常，使用模拟数据
                val mockPosts = if (refresh) {
                    generateMockFavorites(currentUser.id)
                } else {
                    posts + generateMockFavorites(currentUser.id, currentPage)
                }
                posts = mockPosts
                currentPage++
                hasMore = mockPosts.size >= 20
            } finally {
                isLoading = false
                isLoadingMore = false
            }
        }
    }
    
    // 取消收藏
    fun unfavoritePost(post: CommunityPost) {
        coroutineScope.launch {
            try {
                val result = communityApiService.togglePostFavorite(currentUser?.id ?: 0L, post.id)
                result.onSuccess { 
                    posts = posts.filter { it.id != post.id }
                    showDeleteDialog = false
                    postToUnfavorite = null
                    android.util.Log.d("MyFavoritesScreen", "取消收藏成功")
                }.onFailure { error ->
                    android.util.Log.e("MyFavoritesScreen", "取消收藏失败", error)
                    // 即使API失败，也从本地列表中移除（用户体验）
                    posts = posts.filter { it.id != post.id }
                    showDeleteDialog = false
                    postToUnfavorite = null
                }
            } catch (e: Exception) {
                android.util.Log.e("MyFavoritesScreen", "取消收藏异常", e)
                // 即使出现异常，也从本地列表中移除
                posts = posts.filter { it.id != post.id }
                showDeleteDialog = false
                postToUnfavorite = null
            }
        }
    }
    
    // 初始加载
    LaunchedEffect(currentUser) {
        if (currentUser != null) {
            loadFavorites(true)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("我的收藏") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF4361EE),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
            if (isLoading && posts.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = Color(0xFF4361EE)
                    )
                }
            } else if (posts.isEmpty()) {
                EmptyFavoritesState()
            } else {
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    items(posts) { post ->
                        MyFavoriteItem(
                            post = post,
                            onPostClick = {
                                // 跳转到帖子详情页面
                                android.util.Log.d("MyFavoritesScreen", "点击帖子标题，跳转到帖子详情: postId=${post.id}")
                                navController.navigate("postDetail/${post.id.toInt()}")
                            },
                            onUnfavoriteClick = {
                                postToUnfavorite = post
                                showDeleteDialog = true
                            }
                        )
                    }
                    
                    // 加载更多
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF4361EE)
                                )
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 取消收藏确认对话框
    if (showDeleteDialog && postToUnfavorite != null) {
        AlertDialog(
            onDismissRequest = { 
                showDeleteDialog = false
                postToUnfavorite = null
            },
            title = { Text("确认取消收藏") },
            text = { Text("确定要取消收藏这篇帖子吗？") },
            confirmButton = {
                TextButton(
                    onClick = { 
                        postToUnfavorite?.let { unfavoritePost(it) }
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color(0xFFD32F2F)
                    )
                ) {
                    Text("取消收藏")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { 
                        showDeleteDialog = false
                        postToUnfavorite = null
                    }
                ) {
                    Text("保留")
                }
            }
        )
    }
}

@Composable
fun MyFavoriteItem(
    post: CommunityPost,
    onPostClick: () -> Unit,
    onUnfavoriteClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 帖子标题（可点击）
            Text(
                text = post.title ?: "无标题",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF212529),
                modifier = Modifier.clickable { 
                    android.util.Log.d("MyFavoriteItem", "帖子标题被点击: ${post.title}")
                    onPostClick() 
                },
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 帖子摘要（前100字）
            val summary = post.content?.let { content ->
                if (content.length > 100) {
                    content.substring(0, 100) + "..."
                } else {
                    content
                }
            } ?: "无内容"
            
            Text(
                text = summary,
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF6C757D),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 作者和收藏时间
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = "作者: ${post.author ?: "未知"}",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                    Text(
                        text = "收藏时间: ${formatDate(post.createdAt ?: "")}",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                }
                
                // 取消收藏按钮
                IconButton(
                    onClick = onUnfavoriteClick,
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Star,
                        contentDescription = "取消收藏",
                        tint = Color(0xFF6C757D), // 灰色表示取消收藏
                        modifier = Modifier.size(18.dp)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 点赞数和评论数
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.ThumbUp,
                        contentDescription = "点赞",
                        modifier = Modifier.size(14.dp),
                        tint = Color(0xFF6C757D)
                    )
                    Text(
                        text = post.likeCount.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                }
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Comment,
                        contentDescription = "评论",
                        modifier = Modifier.size(14.dp),
                        tint = Color(0xFF6C757D)
                    )
                    Text(
                        text = post.commentCount.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                }
            }
        }
    }
}

@Composable
fun EmptyFavoritesState() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Star,
                contentDescription = null,
                modifier = Modifier.size(64.dp),
                tint = Color(0xFF6C757D)
            )
            Text(
                text = "你还没有收藏任何帖子",
                style = MaterialTheme.typography.titleMedium,
                color = Color(0xFF6C757D)
            )
        }
    }
}

fun generateMockFavorites(userId: Long, page: Int = 1): List<CommunityPost> {
    return listOf(
        CommunityPost(
            id = page * 10 + 1L,
            userId = 1L,
            author = "测试用户1",
            title = "健身心得分享",
            content = "今天想和大家分享一些健身的心得体会。健身不仅仅是锻炼身体，更是一种生活态度。通过坚持锻炼，我不仅收获了健康的身体，还培养了坚强的意志力。",
            likeCount = 15,
            favoriteCount = 8,
            commentCount = 5,
            isLiked = false,
            isFavorited = true,
            createdAt = "2025-09-10T22:30:00",
            updatedAt = "2025-09-10T22:30:00"
        ),
        CommunityPost(
            id = page * 10 + 2L,
            userId = 2L,
            author = "测试用户2",
            title = "营养搭配建议",
            content = "合理的营养搭配对健身效果非常重要。建议大家多吃蛋白质丰富的食物，如鸡胸肉、鸡蛋、牛奶等，同时也要注意碳水化合物的摄入。",
            likeCount = 12,
            favoriteCount = 6,
            commentCount = 3,
            isLiked = true,
            isFavorited = true,
            createdAt = "2025-09-10T21:15:00",
            updatedAt = "2025-09-10T21:15:00"
        )
    )
}
